var net = require('net');

var server = function (callback, _port) {
    var tcp_server = net.createServer();  // 创建 tcp server

    var Sockets = {};
    var SocketID = 1;

    // 监听 端口
    tcp_server.listen(_port || 6000, function () {
        console.log('tcp_server listening 6000');
    });

    // 处理客户端连接
    tcp_server.on('connection', function (socket) {
        console.log(socket.address());
        Sockets[SocketID] = socket;
        SocketID++;
        DealConnect(socket)
    })

    tcp_server.on('error', function () {
        console.log('tcp_server error!');
    })

    tcp_server.on('close', function () {
        console.log('tcp_server close!');
    })


    // 处理每个客户端消息
    function DealConnect(socket) {

        socket.on('data', function (data) {
            // data = data.toString();
            callback && callback(data);
            // 向所有客户端广播消息
            // for (var i in Sockets) {
            //     Sockets[i].write(data);
            // }
            // socket.write(data);
        })

        // 客户端正常断开时执行
        socket.on('close', function () {
            console.log('client disconneted!');
        })
        // 客户端正异断开时执行
        socket.on("error", function (err) {
            console.log('client error disconneted!');
        });
    }

    return {
        send:function (str, unit) {
            var data=str.toString();
            if(unit=="hex"){
                data = str.replace(/-+|\s+/g, "");
            }
            for (var i in Sockets) {
                Sockets[i].write(data);
            }
        }
    }
}


//客户端

var client = function (_options, str, callback) {

    // 指定连接的tcp server ip，端口
    var options = {
        host: '192.168.1.2',
        port: 6000
    }

    var tcp_client = net.Socket();

    // 连接 tcp server
    tcp_client.connect(_options||options, function () {
        console.log('connected to Server');
        tcp_client.write(str||"connect");
    })

    // 接收数据
    tcp_client.on('data', function (data) {
        // console.log('received data: %s from server', data.toString());
        callback && callback(data);
    })

    tcp_client.on('end', function () {
        console.log('data end!');
    })

    tcp_client.on('error', function () {
        console.log('tcp_client error!');
        setTimeout(() => {
            tcp_client.connect(_options||options)
        }, 2000);
    })

    return {
        send:function (str, unit) {
            var data=str.toString();
            if(unit=="hex"){
                data = str.replace(/-+|\s+/g, "");
            }
            tcp_client.write(Buffer.from(data, unit||"ASCII"));
        }
    }
}
